/*
 * MissileView.cpp
 *
 *  Created on: 22.11.2013
 *      Author: dima
 */


#include "MissileView.hpp"

#include "../Resources/IMGLoader.hpp"
#include "../Resources/IMGSplitter.hpp"
#include "../Resources/SoundLoader.hpp"

#include "../Model/MissileModel.hpp"

#include <SDL/SDL_mixer.h>
#include <map>


Tanks::
View::
MissileView::
MissileView(SDL_Surface * argScreen) :
  m_XOffsetExplosion(5),
  m_YOffsetExplosion(5),
  m_screen(argScreen)
{
  Resources::IMGLoader & imgLoader = Resources::IMGLoader::getInstance();
  m_missileImage = imgLoader.GetImage(Resources::Missile);
  m_missileExplosionImage = imgLoader.GetImage(Resources::Explosion);

  Resources::SoundLoader & soundLoader = Resources::SoundLoader::getInstance();
  m_explosionSoundChannel = soundLoader.GetFreeChannel();
}


Tanks::
View::
MissileView::
~MissileView()
{
  Resources::SoundLoader & soundLoader = Resources::SoundLoader::getInstance();
  soundLoader.FreeChannel(m_explosionSoundChannel);
}


void
Tanks::
View::
MissileView::
Draw()
{
  Resources::SoundLoader & soundLoader = Resources::SoundLoader::getInstance();
  Resources::IMGSplitter & imgSplitter = Resources::IMGSplitter::getInstance();

  std::map<Tanks::Model::MissileModel *, Tanks::Model::TankModel *>::iterator missileIter;
  for(missileIter = Tanks::Model::MissileModel::Begin();
      missileIter != Tanks::Model::MissileModel::End();
      ++missileIter)
  {
    Tanks::Model::MissileModel * missile = missileIter->first;
    if(missile->IsExploding())
    {
      if(!Mix_Playing(m_explosionSoundChannel))
      {
        Mix_PlayChannel(m_explosionSoundChannel, soundLoader.GetSound(Tanks::Resources::ExplosionSound), 0);
      }
      std::vector<SDL_Rect> rects = imgSplitter.Animations[Tanks::Resources::ExplosionAnimation];
      SDL_Rect rect = rects[m_currentImages[missile]];
      m_currentImages[missile] = (m_currentImages[missile] + 1) % rects.size();

      SDL_Rect offset;
      offset.x = missile->GetRect()->x - m_XOffsetExplosion;
      offset.y = missile->GetRect()->y - m_YOffsetExplosion;
      SDL_BlitSurface(m_missileExplosionImage, &rect, m_screen, &offset);
    }
    else
    {
      SDL_BlitSurface(m_missileImage, NULL, m_screen, missileIter->first->GetRect());
    }
  }
}

